<?php

namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use App\Models\User;
use App\Models\Administrator;
use GuzzleHttp\Client;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\HttpException;

class TikshopLogin
{
    public function handle($request, Closure $next)
    {
        $data = [
            'tiktokid'=>$request->header('Userid')
        ];
        $validator = Validator::make($data, [
            'tiktokid' => 'required|numeric|digits_between:6,30'
        ]);
        if ($validator->fails()) {
            throw new AuthenticationException();
        }

        $user = User::getUser($data);

        if(!$user){
            //注册
            $rand_nickname = getrandstr_invite_code(6);
            $data['lang'] = $request->header('Lang','en');
            $data['timezone'] = $request->header('Timezone','GMT-04:00');
            //$data['tiktokno'] = $request->header('Customid','@'.$rand_nickname);
            //$data['nickname'] = $request->header('Nickname',$rand_nickname);

            $data['tiktokno'] = $request->header('Customid');
            //$data['nickname'] = $request->header('Nickname');
            $data['nickname'] = $request->header('Customid');

            $data['avatar'] = self::avatarsave($request->header('Avatar',''));
            $data['login_time_last'] = now();

            $ip = $request->ip();
            $data['ip_register'] = $ip;
            $data['ip_last'] = $ip;

            //代理
            $data['agent_id'] = 1;
            if($request->hasHeader('Agent') && strlen($request->header('Agent')) != 6){
                $invite_admin = Administrator::query()->where('invite_code','=',$request->header('Agent'))->first();
                if($invite_admin){
                    $data['agent_id'] = $invite_admin->id;
                }
            }
            $user = User::query()->create($data);
        }else{
            if($user->state == 0){
                //禁用
                throw new HttpException(Response::HTTP_OK, trans('error.10001'), null, [], 10001    );
            }
            if(empty($user->avatar)){
                $user->avatar = self::avatarsave($request->header('Avatar',''));
                $user->save();
            }
        }
        //在线
        Redis::ZADD('userauthlist',Carbon::now()->timestamp,$user->id);
        //在线人数
        //$online_num = Redis::zcount('userauthlist', Carbon::now()->timestamp - 60*5, Carbon::now()->timestamp);

        return $next($request);
    }

    public function avatarsave($avatar){
        $default = "/channels4_profile.jpg";
        return $default;
        if(!empty($avatar)){
            try {
                $extension = pathinfo($avatar)['extension'];
                $path = '/titshop/uploads/avatar/' . Carbon::now()->format('YmdH') .'/'. getrandstr(24).'.'.$extension;
                $file = (new Client())->get($avatar)->getBody();
                if($file){
                    $file2 = Storage::put($path, $file);
                    if($file2){
                        return $path;
                    }
                }
                return $default;
            }catch (\Throwable $throwable) {
                return "";
            }
        }else{
            return $default;
        }
    }

}
